<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rules"
    ref="ruleFormRef"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="代码命名" prop="name" class="inline">
      <el-input
        v-model="ruleForm.name"
        autocomplete="off"
        placeholder="请输入代码命名"
      ></el-input>
    </el-form-item>
    <el-form-item label="预处理类型" prop="pretreatmentType" class="inline">
      <el-radio-group v-model="ruleForm.pretreatmentType">
        <el-radio :label="1">处理header头</el-radio>
        <el-radio :label="2">处理返回结果</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="代码功能描述" prop="description">
      <el-input
        type="textarea"
        v-model="ruleForm.description"
        placeholder="请输入代码功能描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="扩展jar包地址" prop="extendedDependencyPath">
      <el-upload
        class="upload-demo"
        ref="uploadRef"
        action="http://192.168.0.112:8080/api/v1/pretreatmentCode/uploadJar"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button size="small" type="primary">选取文件</el-button>
        </template>
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          >上传</el-button
        >
        <!-- <template #tip>
          <div class="el-upload__tip">
            只能上传 jpg/png 文件，且不超过 500kb
          </div>
        </template> -->
      </el-upload>
    </el-form-item>
    <el-form-item label="java脚本模板" prop="age">
      <el-select
        v-model="ruleForm.codeTemplate"
        placeholder="请选择java脚本模板"
        @change="changeJavaScriptTempalte"
      >
        <el-option
          v-for="item in codeTemplateList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-button
        style="margin-left:10px"
        type="primary"
        @click="addJavaScriptDialog"
        >新增</el-button
      >
    </el-form-item>
    <el-form-item label="模板代码">
      <monaco ref="monacoRef" :opts="opts"></monaco>
    </el-form-item>
    <el-form-item label="数据来源">
      <el-input
        type="textarea"
        :autosize="{ minRows: 5, maxRows: 5 }"
        placeholder="请输入数据来源"
        v-model="ruleForm.dataSources"
      >
      </el-input>
    </el-form-item>
    <el-form-item label="处理结果">
      <el-input
        type="textarea"
        :autosize="{ minRows: 5, maxRows: 5 }"
        v-model="ruleForm.dataResult"
      >
      </el-input>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="testRun">代码执行 </el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>

  <el-dialog title="新增" v-model="dialogVisible" width="width">
    <!-- <el-form :model="form">
      <el-form-item label="" :label-width="">
        <el-input v-model=""></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
    </div> -->
  </el-dialog>
</template>
<script>
import monaco from "@/components/monaco/index.vue";
import { reactive, ref, toRefs, onMounted, watch } from "vue";
export default {
  name: "CodeMirror",
  components: {
    monaco
  },
  setup() {
    const monacoRef = ref(null);
    const uploadRef = ref(null);
    const ruleFormRef = ref(null);
    const mycode = ref(null);
    const state = reactive({
      opts: {
        value: "",
        readOnly: false, // 是否可编辑
        language: "java", // 语言类型
        theme: "vs-dark" // 编辑器主题
      },
      javaContent: "",
      editorOption: {
        // 设置代码编辑器的样式
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
        tabSize: 2,
        fontSize: 20,
        showPrintMargin: false, //去除编辑器里的竖线
        mode: "text/x-java",
        extraKeys: { Tab: "autocomplete" }
      },
      dialogVisible: false,
      fileList: [], // 上传文件列表
      code: "//按Tab键进行代码提示",
      editor: "",
      javaClassName: "",
      ruleForm: {
        name: "",
        pretreatmentType: 1,
        description: "",
        extendedDependencyPath: "",
        codeTemplate: "",
        dataSources: '{"keyA":"10","keyB":"50","keyC":"150"}',
        dataResult: ""
      },
      codeTemplateList: [],
      rules: {
        name: [{ required: true, message: "请输入代码命名", trigger: "blur" }]
      }
    });
    onMounted(() => {
      getTemplate(state.ruleForm.pretreatmentType); // 根据预处理类型获取Java脚本模板
    });
    watch(
      () => state.ruleForm.pretreatmentType,
      () => {
        state.ruleForm.dataResult = "";
        getTemplate(state.ruleForm.pretreatmentType);
      }
    );
    // 获取模板
    const getTemplate = (pretreatmentType) => {
      vm.$axios
        .get("/api/v1/dataengine/codeTemplate/list", {
          params: {
            type: pretreatmentType
          }
        })
        .then((res) => {
          state.codeTemplateList = res.records;
          if (res.records && res.records.length > 0) {
            state.ruleForm.codeTemplate = res.records[0].id;
            state.opts.value = formatterJavaCode(res.records[0].code);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // 上传文件成功回调
    const handleSuccess = (res) => {
      if (res.code == 0 && res.data) {
        vm.$message.success("上传成功");
        state.ruleForm.extendedDependencyPath = res.data;
      }
    };
    const handleRemove = (file, fileList) => {
      console.log(file, fileList);
    };
    // 手动上传文件
    const submitUpload = () => {
      uploadRef.value.submit();
    };
    const changeJavaScriptTempalte = (value) => {
      // 通过id获取模板
      vm.$axios
        .get("/api/v1/dataengine/codeTemplate/getById?id=" + value)
        .then((res) => {
          if (res && res.code) {
            state.opts.value = formatterJavaCode(res.code);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // java 测试运行
    const testRun = () => {
      let extendUrl;
      // 预处理类型
      if (state.ruleForm.pretreatmentType === 1) {
        extendUrl = "/api/v1/pretreatmentCode/dynamicCompileHeaderTest";
      } else if (state.ruleForm.pretreatmentType === 2) {
        extendUrl = "/api/v1/pretreatmentCode/dynamicCompileResultTest";
      }
      vm.$axios
        .post(extendUrl, {
          code: monacoRef.value.getVal(),
          data: state.ruleForm.dataSources,
          extJarPath: [state.ruleForm.extendedDependencyPath]
        })
        .then((res) => {
          state.ruleForm.dataResult = JSON.stringify(res);
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const submitForm = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          vm.$axios
            .post("/api/v1/pretreatmentCode/addCode", {
              codeTemplate: state.ruleForm.codeTemplate, // 代码模板id
              code: monacoRef.value.getVal(), //代码
              extendedDependencyPath: state.ruleForm.extendedDependencyPath, // 依赖包位置
              name: state.ruleForm.name,
              className: state.javaClassName, // 代码类名
              description: state.ruleForm.description,
              pretreatmentType: state.ruleForm.pretreatmentType // 类型
            })
            .then((res) => {
              vm.$message.success("脚本库添加成功！");
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    };
    const resetForm = () => {
      ruleFormRef.value.resetFields();
    };

    const addJavaScriptDialog = () => {
      // state.dialogVisible = true;
      vm.$router.push({
        path: "/manageJavaScriptTemplate",
        query: { addDialog: true }
      });
    };
    // java 格式化
    function formatterJavaCode(code) {
      let pretreatmentType = state.ruleForm.pretreatmentType;
      if (pretreatmentType == 1) {
        state.javaClassName = "HeaderProcessing" + randomString(18);
        code = code.replace("DataEngineHeaderProcessing", state.javaClassName);
      } else if (pretreatmentType == 2) {
        state.javaClassName = "ResultProcessing" + randomString(18);
        code = code.replace("DataEngineResultProcessing", state.javaClassName);
      }
      return code;
    }
    // 生成随机字符串
    function randomString(length) {
      var str =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var result = "";
      for (var i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
      return result;
    }
    return {
      monacoRef,
      uploadRef,
      ruleFormRef,
      mycode,
      ...toRefs(state),
      getTemplate,
      handleSuccess,
      handleRemove,
      submitUpload,
      changeJavaScriptTempalte,
      testRun,
      submitForm,
      resetForm,
      addJavaScriptDialog
    };
  }
};
</script>

<style scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono,
    DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
.demo-ruleForm .el-form-item.inline {
  width: 50%;
  display: inline-block;
}
</style>
